﻿#region namespaces

using System;
using Db4objects.Db4o;
using Db4objects.Db4o.CS;
using Db4objects.Db4o.Ext;

#endregion

namespace ZOIL.DataBackend.Db4o
{
    /// <summary>
    ///     Represents the db4o database client. It connects to a db4o server.
    /// </summary>
    public class Client
    {
        #region Private Fields

        private readonly string _host;
        private readonly int _port;
        private readonly string _username;
        private readonly string _password;

        #endregion

        public Client(string host, int port, string username, string password)
        {
            _host = host;
            _port = port;
            _username = username;
            _password = password;
        }

        /// <summary>
        ///     This is the ObjectContainer that enables us to query for Objects in the database and commit
        ///     changes to the database
        /// </summary>
        private IObjectContainer _objects;

        public IObjectContainer Objects
        {
            get { return _objects; }
            private set { _objects = value; }
        }

        /// <summary>
        ///     connects to the db4o server and returns an ObjectContainer
        /// </summary>
        /// <returns></returns>
        public void Connect()
        {
            try
            {
                //Db4oConfig.ApplyConfig();
                //_objects = Db4oFactory.OpenClient(_host, _port, _username, _password);

                Objects = Db4oClientServer.OpenClient(Db4oConfig.GetClientConfiguration(), _host, _port, _username, _password);
            }
            catch (System.Net.Sockets.SocketException se)
            {
                throw new DatabaseException("Could not connect to database", se);
            }
            catch (InvalidPasswordException)
            {
                throw new DatabaseException("Wrong password given.");
            }
            catch (Exception e)
            {
                throw new DatabaseException("Could not connect to database", e);
            }
        }

        /// <summary>
        ///     closes the connection to the db4o Server
        /// </summary>
        public void CloseConnection()
        {
            try
            {
                _objects.Close();
                _objects = null;
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not close Connection to database. Reason: " + e.Message);
            }
        }
    }
}